#define _CRT_SECURE_NO_WARNINGS 1

#include <vector>
#include <map>
#include <string>
#include <algorithm>

using namespace std;

class Solution {
public:
    struct compare {
        bool operator()(const pair<string, int>& x, const pair<string, int>& y)
        {
            return x.second > y.second || x.second == y.second && x.first < y.first;
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> countmap;
        for (const auto& e : words)
        {
            countmap[e]++;
        }
        vector<pair<string, int>> v(countmap.begin(), countmap.end());
        //stable_sort(v.begin(),v.end());
        sort(v.begin(), v.end(), compare());
        vector<string> retv;
        for (int i = 0; i < k; ++i)
        {
            retv.push_back(v[i].first);
        }
        return retv;
    }
};
